package dao

import (
	"cap/global"
	"github.com/sirupsen/logrus"
	"gorm.io/gorm"
	"lib/db"
	"lib/structs/tables"
)

var DB *gorm.DB

func InitDB() {
	var err error
	DB, err = db.GetDB(global.Conf.DB.Supper, global.Conf.DB.ShowSqlLog, global.Conf.DB.Source, global.Conf.AppFolder)
	if err != nil {
		logrus.Errorf("连接数据库失败：%v", err)
	}
	autoMigrate()
}

func autoMigrate() {
	type vector[T any] []T
	var li = vector[interface{}]{
		&tables.CapAppCollect{},
		&tables.CapCertify{},
		&tables.CapCluster{},
		&tables.CapHost{},
		&tables.CapLink{},
		&tables.CapSession{},
		&tables.CapSessionMapApp{},
	}
	for _, item := range li {
		if !DB.Migrator().HasTable(item) {
			err := DB.AutoMigrate(item)
			if err != nil {
				logrus.Errorf("初始化数据库表结构异常: %v", err)
			}
		}
	}

}
